import {messages, getQueryUrlParam} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Form, Button, message, Modal} from 'antd'
import ApproveBar from 'components/template/approve-bar'
import 'styles/approve/request/approve-request-btn.scss'
import adminApproveListService from 'containers/setting/process-monitoring-platform/admin-approve-list.service'
import borrowService from 'containers/loan-billing/borrow-and-return.service'
import approveService from 'containers/approve/approve.service'
class ApproveLoanBtn extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      passLoading: false,
      rejectLoading: false,
      handUpLoading: false,
      info: {}, //详情
      showAdditionalBtn: false,  //是否显示加签按钮
      showPrintBtn: false,  //是否显示审批中打印按钮
      preApproveOIDs: [], //当前审批链中已审批用户的OID
      // TODO 只改了废弃的key，还需修改返回逻辑
      approveLoanList: menuRoute.getRouteItem('to-be-approve', 'key'), //申请单审批列表页
      signCompanyOIDs:[],
      admin:false,
      showApproveTransferBtn: false
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!this.state.info.loanBillOID && nextProps.approving) {
      this.setState({
        info: nextProps.info,
      }, () => {
        this.showAdditional();
        this.getPreApproveOID()
      })
    }
    this.showPrint(nextProps.info);
    this.showApproveTransferBtn(nextProps.formInfo);
    this.setState({
      admin:nextProps.info.admin
    })
  }

  showApproveTransferBtn = formInfo => {
    this.setState({showApproveTransferBtn: formInfo.customFormPropertyMap && formInfo.customFormPropertyMap['approvalIsDeliver'] === 'true'});
  };

  //判断是否可以打印
  showPrint = (info) => {
    if (this.props.profile['Approver.print.enabled'] && info.printButtonDisplay) {
      this.setState({showPrintBtn: true});
    }
  };

  handlePrint = () => {
    const {info} = this.props;
    borrowService.printLoanApplication(info.loanBillOID).then(res => {
      window.open(res.data.link, '_blank')
    }).catch((err) => {
      message.error(err.response.data.message);
    })
  };

  //判断是否可以加签
  showAdditional = () => {
    const { info } = this.state, { company } = this.props;
    let params = {
      companyOID: company.companyOID,
      formOID: info.formOID,
      counterSignType: 'enableAddSign',
      approverOID: getQueryUrlParam('approverOID'),
      entityOID: info.loanBillOID,
      entityType: 3001
    };
    this.props.approving && this.state.info.formOID && (
      borrowService.postAddSignEnableScope(params).then(res =>{
        if (res.data.enabled) {
          //加签人范围
          this.setState({
            showAdditionalBtn: res.data.enabled,
            signCompanyOIDs: res.data.approvalAddSignScope.companyOIDs
          });
        }
      })
    )
  };

  //获取当前审批链中已审批的用户OID
  getPreApproveOID = () => {
    let preApproveOIDs = [];
    (this.state.info.approvalHistorys || []).map(item => {
      item.operation === 2001 && (preApproveOIDs.push(item.operatorOID))
    });
    this.setState({ preApproveOIDs })
  };

  //提示 当前被加签的人是否在已审批的人中
  hasRepeatApproveTip = (value, additionalItems, priceAuditor) => {
    let additionalOIDs = [];
    let additionalHaveApprovedNames = [];  //加签人中已审批的用户名
    additionalItems.map(item => {
      additionalOIDs.push(item.userOID)
    });
    additionalOIDs.map((OID, index) => {
      if (this.state.preApproveOIDs.indexOf(OID) > -1) {
        additionalHaveApprovedNames.push(additionalItems[index].fullName)
      }
    });
    if (additionalHaveApprovedNames.length) {
      Modal.confirm({
        title: `${additionalHaveApprovedNames.join('、')} ${messages('approve.key86'/*已经审批通过，是否继续*/)}？`,
        onOk: () => this.handleApprovePass(value, additionalOIDs, priceAuditor)
      });
    } else {
      this.handleApprovePass(value, additionalOIDs, priceAuditor)
    }
  };

  //审批通过
  handleApprovePass = (value, additionalOIDs, priceAuditor) => {
    let params = {
      approvalTxt: value,
      entities: [{
        approverOID: getQueryUrlParam('approverOID'),
        entityOID: this.state.info.loanBillOID,
        entityType: 3001,
        countersignApproverOIDs: additionalOIDs,
        priceAuditor
      }]
    };
    this.setState({ passLoading: true });
    let service;
    if(this.state.admin){
      service = adminApproveListService;
    }else{
      service = borrowService;
    }
    service.handleRequestApprovePass(params).then(res => {
      if (res.data.failNum === 0) {
        message.success(messages('common.operate.success'));
        this.setState({ passLoading: false });
        this.goBack()
      } else {
        this.setState({ passLoading: false });
        message.error(`${messages('common.operate.filed')}，${res.data.failReason[this.state.info.loanBillOID]}`)
      }
    }).catch(e => {
      this.setState({ passLoading: false });
      message.error(`${messages('common.operate.filed')}，${e.response.data.message}`)
    })
  };

  //审批驳回
  handleApproveReject = (value, additionalItems) => {
    let additionalOIDs = [];
    additionalItems.map(item => {
      additionalOIDs.push(item.userOID)
    });
    let params = {
      approvalTxt: value,
      entities: [{
        approverOID: getQueryUrlParam('approverOID'),
        entityOID: this.state.info.loanBillOID,
        entityType: 3001, //申请单
      }]
    };
    this.setState({ rejectLoading: true });
    let service;
    if(this.state.admin){
      service = adminApproveListService;
    }else{
      service = borrowService;
    }
    service.handleRequestApproveReject(params).then(res => {
      if (res.data.failNum === 0) {
        message.success(messages('common.operate.success'));
        this.setState({ rejectLoading: false });
        this.goBack()
      } else {
        this.setState({ rejectLoading: false });
        message.error(`${messages('common.operate.filed')}，${res.data.failReason[this.state.info.loanBillOID]}`)
      }
    }).catch(e => {
      this.setState({ rejectLoading: false });
      message.error(`${messages('common.operate.filed')}，${e.response.data.message}`)
    })
  };

  //返回
  goBack = () => {
    const {approveLoanList} = this.state;
    let backUrl = this.props.backUrlKey ? this.getKeyUrl(this.props.backUrlKey) :
      (this.state.admin ? menuRoute.getRouteItem('process-monitoring-platform', 'key').url : approveLoanList.url + '?tab=approving');
    this.context.router.push(backUrl);
  };

  afterClose = (res) => {
    res === 'success' && window.history.go(-1);
  };

  getKeyUrl = (key) => {
    let urlInfo = menuRoute.getRouteItem(key, 'key');
    return urlInfo.url;
  };

  //暂挂单据
  handleApproveHangUp = () => {
    const { info } = this.state;
    let params = {
      entities: [{
        approverOID: getQueryUrlParam('approverOID'),
        entityOID: info.loanBillOID,
        entityType: 3001
      }]
    };
    this.setState({handUpLoading: true});
    approveService.handleEntityHangUp(params).then(res => {
      this.setState({handUpLoading: false});
      if (res.data.failNum === 0) {
        message.success(messages('common.operate.success'));
        this.goBack();
      } else {
        message.error(`${messages('common.operate.filed')}，${res.data.failReason[this.state.info.applicationOID]}`);
      }
    }).catch(e => {
      this.setState({handUpLoading: false});
      message.error(`${messages('common.operate.filed')}，${e.response.data.message}`);
    });
  };

  //是否展示挂起
  isShowHangUp = () => {
    const { info } = this.state;
    let showHangUp = false;
    let approverOID = getQueryUrlParam('approverOID');
    info.approvalChains && info.approvalChains.map(chain => {
      if (chain.approverOID === approverOID && chain.pending) {
        showHangUp = true;
      }
    });
    return showHangUp;
  };

  render() {
    const { passLoading, rejectLoading, approveLoanList, showAdditionalBtn, showPrintBtn, signCompanyOIDs, handUpLoading, showApproveTransferBtn } = this.state;
    let moreButtons = [];
    !this.isShowHangUp() && moreButtons.push('hangUp');
    showAdditionalBtn && moreButtons.push('additional');
    showPrintBtn && moreButtons.push('print');
    showApproveTransferBtn && moreButtons.push('approveTransfer');
    let backUrl = this.props.backUrlKey ? this.getKeyUrl(this.props.backUrlKey) : (this.state.admin ? menuRoute.getRouteItem('process-monitoring-platform', 'key').url
      : approveLoanList.url + '?tab=approving');
    moreButtons = this.state.admin ? [] : moreButtons;
    return (
      <div className="approve-request-btn">
        {this.props.approving ? (
          <ApproveBar backUrl={backUrl}
                      admin={this.state.admin}
                      signCompanyOIDs={signCompanyOIDs}
                      moreButtons={moreButtons}
                      handleApproveHangUp={this.handleApproveHangUp}
                      allLoading={passLoading || rejectLoading || handUpLoading}
                      customFormPropertyMap={this.props.formInfo ? this.props.formInfo.customFormPropertyMap : {}}
                      entities={{
                        approverOID: getQueryUrlParam('approverOID'),
                        entityOID: this.state.info.loanBillOID,
                        entityType: 3001,
                        applicantOID: this.state.info.applicantOID,
                        businessCode: this.state.info.businessCode,
                        formOID: this.state.info.formOID
                      }}
                      handleApproveTransfer={() => {
                        this.goBack();
                      }}
                      handleApproveAdditional={() => {
                        this.goBack();
                      }}
                      buttons={ ( getQueryUrlParam('approvalMode') !== '1005' && this.state.admin  ?['reject','pass']:undefined)}
                      handleApproveSkip={this.afterClose}
                      handleApprovePrint={this.handlePrint}
                      handleApprovePass={this.hasRepeatApproveTip}
                      handleApproveReject={this.handleApproveReject}/>
        ) : (
          <div>
            {showPrintBtn && !this.state.admin &&
            <Button type="primary" style={{marginRight: 10}} onClick={this.handlePrint}>{messages("common.print")/*打印*/}</Button>
            }
            <Button onClick={this.goBack} className="back-btn">{messages("common.back")/*返回*/}</Button>
          </div>
        )}
      </div>
    )
  }
}

ApproveLoanBtn.propTypes = {
  info: React.PropTypes.object,
  formInfo: React.PropTypes.object,
  approving: React.PropTypes.bool,
  backUrlKey: React.PropTypes.string //返回URLKey 修改人：陈行健
};

ApproveLoanBtn.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    profile: state.login.profile
  }
}

const wrappedApproveLoanBtn = Form.create()(ApproveLoanBtn);

export default connect(mapStateToProps)(wrappedApproveLoanBtn)
